﻿/**
*
*  RSSReader is a lightweight RSS client written in C#
*
*  Copyright 2012 Ashot Aslanyan <ashot.aslanian@gmail.com>
*
*  This file is part of RSSReader.
*
*  RSSReader is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  RSSReader is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with servmonitor.  If not, see <http://www.gnu.org/licenses/>.
*
*/

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Threading;
using System.Collections.Generic;

namespace RSSReader
{
    public partial class FormView
    {
        /// <summary>
        /// Event handler for <see cref="System.Windows.Forms.Form.Shown"/> event
        /// </summary>
        /// <param name="e"></param>
        private void FormView_Shown(Object sender, EventArgs e)
        {
            Thread UpdateFeeds = new Thread(this.UpdateFeedsBackgroundWorker);

            Logger.Instance.Log("FormView", "started thread to update tree");
            UpdateFeeds.Start();
        }

        private void FormView_Resize(Object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
            {
                this.Hide();
                this.NotificationIcon.BalloonTipText = "Application is still running.\nRight-click and press \"Exit\", if you want to quit.";
                this.NotificationIcon.ShowBalloonTip(500);
            }
        }

        void FormView_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void NotificationIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void UpdateFeedsBackgroundWorker()
        {
            Logger.Instance.Log("FormView", "trying to update feeds");

            for (int i = 0; i < this.RSSFeed.Count; i++)
            {
                for (int j = 0; j < this.RSSFeed[i].items.Count; j++ )
                {
                    this.RSSFeed[i].items[j] = null;
                }

                this.RSSFeed[i] = null;
            }

            this.RSSFeed = new List<RSSObject>();
            this.GetFeeds();
            this.Items.Invoke(new RefreshTree(this.RefreshTreeView), false);

            Thread.Sleep(120 * 1000);

            Logger.Instance.Log("FormView", "started thread to update tree");

            Thread UpdateFeeds = new Thread(this.UpdateFeedsBackgroundWorker);

            UpdateFeeds.Start();
        }

        private void AddFeed_Click(object sender, EventArgs e)
        {
            InputMessageBox _InputMessageBox = new InputMessageBox();
            DialogResult result = _InputMessageBox.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                try
                {
                    using (StreamWriter r = System.IO.File.AppendText(RSSReaderApplication.AppDataPath + "rssreader.conf"))
                    {
                        r.WriteLine(_InputMessageBox.url);
                    }

                    Logger.Instance.Log("FormView", "adding new item to feeds.");
                    this.RSSFeed.Add(RSSReader.getFeed(new Uri(_InputMessageBox.url)));
                    Logger.Instance.Log("FormView", String.Format("currently there are {0} feeds in library.", RSSFeed.Count));

                    Logger.Instance.Log("FormView", "refreshing list...");
                    this.RefreshTreeView(false);
                    Logger.Instance.Log("FormView", "refreshed.");
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log("FormView", "exception caught while trying to add new url to config file.");
                    Logger.Instance.Log("FormView", String.Format("exception message: {0}", ex.Message));
                }
            }

        }

        private void About_Click(object sender, System.EventArgs e)
        {
            AboutBox _AboutBox = new AboutBox();
            _AboutBox.ShowDialog(this);
        }


        private void Quit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you really want to quit?", "Exit", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void Items_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                System.Drawing.Point p = new System.Drawing.Point(e.X, e.Y);

                TreeNode node = this.Items.GetNodeAt(p);
                this.Items.SelectedNode = node;

                if (node != null && node.Parent == null)
                {
                    this.ItemsContextMenu.Show(this.Items, p);
                }
            }
        }

        private void Items_Click(object sender, TreeViewEventArgs e)
        {
            if (this.Items.SelectedNode.Parent != null)
            {
                int pid = this.Items.SelectedNode.Parent.Index;
                int cid = this.Items.SelectedNode.Index;

                this.Items.SelectedNode.NodeFont = new System.Drawing.Font(this.Font, System.Drawing.FontStyle.Regular);
                this.Message.DocumentText = this.RSSFeed[pid].items[cid].description;
                this.RSSFeed[pid].items[cid].isRead = true;

                Logger.Instance.Log("FormView", String.Format("updating xml file {0}", this.RSSFeed[pid].filename));
                XDocument doc = XDocument.Load(this.RSSFeed[pid].filename);

                doc.Root.Element("channel").Elements("item")
                    .Single(item => System.Int32.Parse(item.Attribute("id").Value) == this.RSSFeed[pid].items[cid].id)
                    .SetAttributeValue("isRead", 1);

                doc.Save(this.RSSFeed[pid].filename);
                Logger.Instance.Log("FormView", "updated");

                Logger.Instance.Log("FormView", "updating tree");
                this.RSSFeed[pid].unreadItems = this.RSSFeed[pid].items.Count(i => i.isRead == false);

                if (this.RSSFeed[pid].unreadItems > 0)
                {
                    this.Items.Nodes[pid].NodeFont = new System.Drawing.Font(this.Items.Font, System.Drawing.FontStyle.Bold);
                    this.Items.Nodes[pid].Text = String.Format("{0} ({1})", this.RSSFeed[pid].title, this.RSSFeed[pid].unreadItems);
                }
                else
                {
                    this.Items.Nodes[pid].NodeFont = new System.Drawing.Font(this.Items.Font, System.Drawing.FontStyle.Regular);
                    this.Items.Nodes[pid].Text = String.Format("{0}", this.RSSFeed[pid].title);
                }
                Logger.Instance.Log("FormView", "updated");
            }
            else
            {
                this.Message.DocumentText = this.RSSFeed[this.Items.SelectedNode.Index].items[0].description;
            }
        }

        private void MarkAllAsRead_Click(object sender, EventArgs e)
        {
            int feedID = this.Items.SelectedNode.Index;

            XDocument doc = XDocument.Load(this.RSSFeed[feedID].filename);

            System.Collections.Generic.List<XElement> items = doc.Root.Element("channel").Elements("item").ToList();

            foreach (XElement item in items)
            {
                item.SetAttributeValue("isRead", 1);
            }

            doc.Save(this.RSSFeed[feedID].filename);

            this.RSSFeed[feedID].unreadItems = 0;
            this.RefreshTreeView(true);

            this.Items.Nodes[feedID].Expand();
        }
    }
}
